#include "script_base.hpp"
#include <exception>
#include <filesystem>
#include <memory>
#include <string>
#include <unordered_map>
#include "gui/texture.hpp"
#include "scripting/scripting_api.h"
#include "utils/log.hpp"
#include "utils/path_utils.hpp"
#include "gui/texture_ids.hpp"
#include "gui/texture.hpp"

static std::unordered_map<std::string, int> texture_id_map = {
    {"angelscript", Tex_Script_AngelScript},
    {"generic", Tex_Script_Generic},
    {"js", Tex_Script_JS},
    {"lua", Tex_Script_Lua},
    {"py", Tex_Script_Py},
    {"python", Tex_Script_Python},
    {"quirrel", Tex_Script_Quirrel},
    {"wren", Tex_Script_Wren},
};

ScriptExtension::~ScriptExtension () {
    delete script_;
}

TexturePtr ScriptExtension::icon () const
{
    std::string lang = script_->lang();
    auto it = texture_id_map.find(lang);
    if (it == end(texture_id_map))
        return TextureManager::Get(Tex_Script_Generic);
    return TextureManager::Get(it->second);
}

ScriptExtension::ScriptExtension (IScript *script, double file_time) : script_ (script), file_time_ (file_time)
{
    assert (script != nullptr && "NULL script?");
}

ScriptUsage ScriptExtension::usage() const
{
    return script_->usage();
}

const char *ScriptExtension::title () const
{
    return script_->title ();
}

const char *ScriptExtension::file () const
{
    return script_->file ();
}

bool ScriptExtension::reloadable () const
{
    return script_->reloadable ();
}

double ScriptExtension::time () const
{
    return file_time_;
}

bool ScriptExtension::reload ()
{
    return script_->reload ();
}

bool ScriptExtension::call (const void *arg) const
{
    try
    {
        return script_->call (arg);
    }
    catch (std::exception &e)
    {
        L_ERROR ("script call with exception: %s", e.what ());
        return false;
    }
}
